// Using the jQuery document ready function, do things to initialize the script
$(document).ready(function() {

	// Load the current list of messages
	$.get('php/leaf.php', function(reply) { showMessages(reply); });
	
	// Attach the event handler to the about us, home, and stats buttons
	$('#homelink').click(function() { window.location.reload(); });
	$('#aboutlink').click(function() { $('#maincontent').load('about.html'); });
	
	$('#statslink').click(function() { 
		$('#maincontent').load('stats.html', function() {
			// After the load is performed, call the function to calculate and display the stats
			calcStats();
			// Also add that functionality to the recalculate button
			$('#calc_button').click(calcStats);
		}); 
	});
	
	// Attach the event handler to the leaf it button
	$('#submit_button').click(submitButton);
	
	// Attach the event handler to the refresh button
	$('#refresh_button').click(function() {
		// Make a get request for the newest messages
		$.get('php/leaf.php', function(reply) { showMessages(reply); });
	});

});


// This function handles the click of the submit button
function submitButton() {
	// Store the message entered and blank the field
	inputMessage = $('#message_input').val();
	$('#message_input').val('');
	
	// Do nothing if the input message is blank
	if(inputMessage == '') return;
	
	// Create the POST data that contains the message to be added to the database
	data = { message: inputMessage };
	// Send the POST request and process the reply
	$.post('php/leaf.php', data, function(reply) { showMessages(reply); });
}


// Function to display the messages returned by the server, takes a JSON object
function showMessages(reply) {
	
	// Parse the JSON object into an array of messages
	var messages = JSON.parse(reply);
	// Get rid of the old message listing
	$('#messages').empty();
	
	// Go through each message and append it onto the page
	for( message in messages) {
		$('#messages').append('<img id="leafbullet" src="images/leafbullet.png" /><p>' + messages[message] + '</p>');
	}
}

// This function takes care of calculating and displaying the stats
function calcStats() {
	// Grab the messages from the server
	$.get('php/leaf.php', function(reply) {
		
		// Variable to store the running character count
		var totalCharacters = 0;
		
		// Parse the JSON object into an array of messages
		var messages = JSON.parse(reply);
		
		// Go through and add up all of the characters
		for( message in messages) {
			totalCharacters += messages[message].length;
		}
		
		// Display the total number of messages, total characters, and average
		$('#total_messages').text(messages.length);
		$('#total_characters').text(totalCharacters);
		$('#average_length').text(parseInt(totalCharacters / messages.length));
	});
}